/*
 * meituan.com Inc.
 * Copyright (c) 2010-2018 All Rights Reserved.
 */
package java.zk.example;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;

/**
 * <p>
 * ZK客户端管理工具
 * </p>
 * @author LvJing
 * @version $Id:AdminClient.java v1.0 2018/9/2 下午12:08 LvJing Exp $
 */
public class AdminClient implements Watcher {

    private static final Logger log = LoggerFactory.getLogger(Client.class);

    private ZooKeeper zk;

    private String hostPort;

    public AdminClient(String hostPort) {
        this.hostPort = hostPort;
    }

    public void startZK() throws IOException {
        this.zk = new ZooKeeper(hostPort, 150000, this);
    }

    @Override
    public void process(WatchedEvent event) {
        log.info("WatchedEvent:{}, hostPort:{}", event, hostPort);
    }

    public void listState() throws KeeperException, InterruptedException {
        try {
            Stat stat = new Stat();
            byte[] data = zk.getData("/master", false, stat);
            log.info("Master:{}, since:{}", new String(data), new Date(stat.getCtime()).toLocaleString());
        } catch (KeeperException.NoNodeException e) {
            log.warn("Master not exist");
        }
        zk.getChildren("/workers", false).forEach(worker -> {
            try {
                byte[] workerData = zk.getData("/workers/" + worker, false, null);
                log.info("Worker:{}", new String(workerData));
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        });
        zk.getChildren("/assign", false).forEach(assign -> {
            try {
                byte[] data = zk.getData("/assign/" + assign, false, null);
                log.info("Task:{}", new String(data));
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    public void exists() {
        zk.exists("/master", event -> {
            log.info("EventType:{}", event.getType());
        }, (rc, path, ctx, stat) -> {
            log.info("result:{}", KeeperException.Code.get(rc));
        }, null);
    }

    public static void main(String[] args) throws Exception {
        AdminClient adminClient = new AdminClient("127.0.0.1:2181");
        adminClient.startZK();
        adminClient.listState();
    }
}
